package com.tange.ai.iot.client.gnssa.home

import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnLongClickListener
import android.view.ViewGroup
import android.view.Window
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.PopupMenu
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.util.Consumer
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import base.http.rxandroid.CustomDisposableForJava
import base.http.utils.RetrofitManager
import base.utils.LogUtil
import base.utils.SysUtils
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.clj.fastble.data.BleDevice
import com.permissionx.guolindev.PermissionX
import com.tange.ai.iot.client.gnssa.BuildConfig
import com.tange.ai.iot.client.gnssa.Constants
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.bean.BleSLDevice
import com.tange.ai.iot.client.gnssa.bean.DevicesListBean
import com.tange.ai.iot.client.gnssa.bean.DevicesListBean.RowsBean
import com.tange.ai.iot.client.gnssa.bean.RespMsg
import com.tange.ai.iot.client.gnssa.binding.BindingQrcodeScanActivity
import com.tange.ai.iot.client.gnssa.binding.BindingWaysActivity
import com.tange.ai.iot.client.gnssa.databinding.ActivityHomeBinding
import com.tange.ai.iot.client.gnssa.httpservice.DeviceService
import com.tange.ai.iot.client.gnssa.internal.DebuggingQrcodeScanActivity
import com.tange.ai.iot.client.gnssa.internal.TokenQrcodeScanActivity
import com.tange.ai.iot.client.gnssa.lan.LanApScanActivity
import com.tange.ai.iot.client.gnssa.newui.EventBusEntity
import com.tange.ai.iot.client.gnssa.newui.WiFiActivity
import com.tange.ai.iot.client.gnssa.play.DeviceLiveActivity
import com.tange.ai.iot.client.gnssa.play.multi.MultiChannelDeviceLiveActivity
import com.tange.ai.iot.client.gnssa.play.multi.SharedChannelDeviceLiveActivity
import com.tange.ai.iot.client.gnssa.token.InternalAccountLoginActivity
import com.tange.ai.iot.client.gnssa.token.InternalAccountModifyActivity
import com.tange.ai.iot.client.gnssa.utils.BleUtil
import com.tange.ai.iot.client.gnssa.utils.SP
import com.tange.ai.iot.client.gnssa.utils.ble.BleScan
import com.tange.ai.iot.client.gnssa.view.popup.NormalMsgHPopup
import com.tange.ai.iot.client.gnssa.view.popup.NormalMsgVPopup
import com.tange.base.toolkit.ClipboardUtils
import com.tange.base.toolkit.PreferenceUtil
import com.tange.base.toolkit.StatusBarUtil
import com.tange.base.toolkit.StatusNavUtils
import com.tange.base.toolkit.Tips
import com.tange.base.toolkit.gone
import com.tange.base.toolkit.isVisible
import com.tange.base.toolkit.mainHandler
import com.tange.base.toolkit.onClicked
import com.tange.base.toolkit.paddingStatusBar
import com.tange.base.toolkit.ui
import com.tange.base.toolkit.visible
import com.tange.base.ui.design.BasicDialogInput
import com.tange.base.ui.design.BasicDialogLoading
import com.tange.base.ui.design.BasicDialogRequest
import com.tange.core.access.token.Authentication
import com.tange.core.builtin.account.BuiltinAccount
import com.tange.core.device.facade.ConnectStatus
import com.tange.core.device.facade.DeviceFacade
import com.tange.core.device.manage.DeviceBattery
import com.tange.core.device.manage.DeviceInfoBasic
import com.tange.core.device.manage.DeviceInfoQuery
import com.tange.core.device.manage.DeviceOnlineStatus
import com.tange.core.device.manage.DeviceThumbnail
import com.tange.core.device.manage.DeviceUnbind
import com.tange.core.message.distribution.MessagePush
import com.tange.core.sharing.DeviceSharing
import com.tange.core.trouble.shooting.entry.DebuggingAssistant
import com.tange.core.trouble.shooting.logging.RuntimeLogging
import com.tange.feature.binding.connect.ap.DeviceBindingConnectionByAccessPoint
import com.tange.feature.binding.search.DeviceBindingSearchAccessPoint
import com.tg.appcommon.android.TGLog
import io.reactivex.android.schedulers.AndroidSchedulers
import org.greenrobot.eventbus.EventBus


class HomeActivity : AppCompatActivity() {

    companion object {
        const val TAG = "HomeActivity_"
        private const val VIEW_TYPE_DEVICE = 0
        private const val VIEW_TYPE_MORE = 1
        private const val PAGE_LIMIT = 10

        const val INTENT_ACTION_RING = "ring_request"
        const val PARAM_DEVICE_ID = "device_id"
        const val PARAM_DEBUGGING_MODE = "debugging_mode"

        private const val PRE_CONNECT_DEVICE_COUNT = 1
    }

    private lateinit var binding: ActivityHomeBinding

    private lateinit var listAdapter: ListAdapter

    private val devices = ArrayList<Device>()

    private var loading: BasicDialogLoading? = null

    private var bindingPrepareRemind = false

    // 用于演示设备提前连接这一场景（目的是提升后续查看实时时的出图速度）
    // 此处设计的预连策略为：拉下来的前3台设备，如果在线，那么建立连接。
    // 务必注意： 这里只是给出一个示例，建议您结合自身业务场景，设计最适合的预连策略。
    private val deviceFacadeMapping = HashMap<String, DeviceFacade>()
    private val deviceConnectStatusObserver = Consumer<ConnectStatus> {
        Log.i(TAG, "[preConnect][status] ${it.deviceId} --- ${it}")
        if (preConnectToDevice && !preConnectSuccessNotified) {
            preConnectSuccessNotified = true
            Tips.show("${it.deviceId} 提前连接成功")
        }
    }

    private val ringReceiver: LocalBroadcastReceiver = LocalBroadcastReceiver()

    private var mediaPlayer: MediaPlayer? = null

    private var debuggingMode = false

    private var refreshLater = true

    private var pushBindingCanRetry = true

    private var searchKeyword = ""

    // 是否启用设备预连策略（根据你自己APP的实际产品需求而定）
    private var preConnectToDevice = false
    private var preConnectSuccessNotified = false

    private var mBleDeviceAdapter: BaseQuickAdapter<BleSLDevice, BaseViewHolder>? = null

    private lateinit var apSearch: DeviceBindingSearchAccessPoint
    private var apSearchList = ArrayList<String>()

    data class Device(
        var deviceInfoBasic: DeviceInfoBasic? = null,
        var deviceOnlineStatus: DeviceOnlineStatus? = null,
        var deviceThumbnail: DeviceThumbnail? = null,
        var deviceBattery: DeviceBattery? = null,
        var rowsBean: RowsBean? = null
    )

    private var count = 0
    private var handler = Handler()
    private var runnable = Runnable {
        showSearchText()
    }

    var deviceService: DeviceService = RetrofitManager().getDefaultClient(DeviceService::class.java)


    private fun showSearchText() {
        count++
        if (count % 4 == 1) {
            binding.tvSearchDevices.text = "."
        } else if (count % 4 == 2) {
            binding.tvSearchDevices.text = ".."
        } else if (count % 4 == 3) {
            binding.tvSearchDevices.text = "..."
        } else {
            binding.tvSearchDevices.text = ""
        }
        handler.postDelayed(runnable, 500)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setLightStatusBar(this, true)
        StatusNavUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_background))
        debuggingMode = intent.getBooleanExtra(PARAM_DEBUGGING_MODE, false)
        preConnectToDevice = SP.getBoolean(this, Constants.KEY_ENABLE_PRE_CONNECT, false)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        binding = ActivityHomeBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            root.paddingStatusBar()
        }

        binding.swipeRefresh.apply {
            setProgressBackgroundColorSchemeColor(
                ContextCompat.getColor(
                    this@HomeActivity,
                    R.color.basic_color_blue
                )
            )
            setColorSchemeColors(Color.WHITE)
            setOnRefreshListener {
                devices.clear()
                requireDeviceList()
            }
        }

        listAdapter = ListAdapter()
        binding.apList.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.apList.adapter = listAdapter

        loading = BasicDialogLoading(this).apply {
            setMessage("刷新中...")
        }

        binding.add.onClicked { onAddDevice(it) }

        binding.retry.onClicked { requireDeviceList() }

        binding.logout.onClicked { logout() }

        binding.search.onClicked { onSearch() }

        binding.llConnectWifi.onClicked {
            binding.ivConnectWifi.setImageResource(R.drawable.icon_wifi2)
            binding.tvConnectWifi.setTextColor(baseContext.resources.getColor(R.color.basic_color_blue))
            binding.ivDevices.setImageResource(R.drawable.icon_devices1)
            binding.tvDevices.setTextColor(baseContext.resources.getColor(R.color.basic_color_black))
            binding.ivMine.setImageResource(R.drawable.icon_mine1)
            binding.tvMine.setTextColor(baseContext.resources.getColor(R.color.basic_color_black))
            binding.llConnectWifiLayout.visible()
            binding.rlDeviceListLayout.gone()
            binding.llAccountLayout.gone()

//            if ("手动发现"==binding.tvManualSearch.text) {
//                binding.llConnectWifiAuto.visible()
//                binding.llConnectWifiManual.gone()
//            } else {
//                binding.llConnectWifiAuto.gone()
//                binding.llConnectWifiManual.visible()
//            }

            requestLocationPermission()

        }

        binding.llDevices.onClicked {
            binding.ivConnectWifi.setImageResource(R.drawable.icon_wifi1)
            binding.tvConnectWifi.setTextColor(baseContext.resources.getColor(R.color.basic_color_black))
            binding.ivDevices.setImageResource(R.drawable.icon_devices2)
            binding.tvDevices.setTextColor(baseContext.resources.getColor(R.color.basic_color_blue))
            binding.ivMine.setImageResource(R.drawable.icon_mine1)
            binding.tvMine.setTextColor(baseContext.resources.getColor(R.color.basic_color_black))
            binding.llConnectWifiLayout.gone()
            binding.rlDeviceListLayout.visible()
            binding.llAccountLayout.gone()

        }

        binding.llMine.onClicked {
            binding.ivConnectWifi.setImageResource(R.drawable.icon_wifi1)
            binding.tvConnectWifi.setTextColor(baseContext.resources.getColor(R.color.basic_color_black))
            binding.ivDevices.setImageResource(R.drawable.icon_devices1)
            binding.tvDevices.setTextColor(baseContext.resources.getColor(R.color.basic_color_black))
            binding.ivMine.setImageResource(R.drawable.icon_mine2)
            binding.tvMine.setTextColor(baseContext.resources.getColor(R.color.basic_color_blue))
            binding.llConnectWifiLayout.gone()
            binding.rlDeviceListLayout.gone()
            binding.llAccountLayout.visible()
            binding.tvCacheSize.text = SysUtils.getTotalCacheSize(baseContext)

        }

        binding.clCleanCache.onClicked {
            showCacheDialog()
        }

        binding.llDevices.performClick()

        // 演示修改密码
        binding.logout.setOnLongClickListener {
            startActivity(Intent(this@HomeActivity, InternalAccountModifyActivity::class.java))
            true
        }

        binding.tvManualSearch.onClicked {
//            if ("手动发现"==binding.tvManualSearch.text) {
//                gotoManualSearch()
//            } else {
//                binding.llConnectWifiAuto.visible()
//                binding.llConnectWifiManual.gone()
//                binding.tvManualSearch.text = "手动发现"
//            }

            gotoManualSearch()
        }

        binding.tvGoToManualSearch.onClicked {
            gotoManualSearch()
        }

        binding.logoutV2.onClicked {
            var normalMsgDialog =
                NormalMsgVPopup(baseContext)
            normalMsgDialog.showPopupWindow()
            normalMsgDialog.tvTitle.text = "温馨提示"
            normalMsgDialog.tvContent.text =
                "确定退出登录吗"
            normalMsgDialog.tvCancel.visibility = View.VISIBLE
            normalMsgDialog.tvCancel.text = "取消"
            normalMsgDialog.tvSure.text = "确定"
            normalMsgDialog.tvSure.onClicked {
                normalMsgDialog.dismiss()
                try {
                    logout()
                } catch (e: java.lang.Exception) {
                    // 处理异常，例如在非Activity的Context中使用
                }
            }

        }

        LocalBroadcastManager.getInstance(this)
            .registerReceiver(ringReceiver, IntentFilter(INTENT_ACTION_RING))

        pushServiceBinding()


        // 这是为了方便定位问题。不要参考此做法。你开发 APP 时应当 仅 在调试问题时启用（DEBUG包下）
        RuntimeLogging.enableDebugMode(true)

        // 添加诊断助手
        DebuggingAssistant.attach(this, binding.help, true)

        mBleDeviceAdapter = object :
            BaseQuickAdapter<BleSLDevice, BaseViewHolder>(R.layout.item_scan_ble_v2) {
            override fun convert(holder: BaseViewHolder, item: BleSLDevice) {
                holder.setText(
                    R.id.tv_device_name,
                    "BleName:" + item.bleDevice.name + "\nuuid:" + item.tangeUUID + "\nMac:" + item.wifiMac + "\nPID:" + item.pId
                )
                var checkBox = holder.itemView.findViewById<CheckBox>(R.id.cb)
                checkBox.isChecked = item.isSelect

                checkBox.onClicked {
                    item.isSelect = checkBox.isChecked
                    notifyDataSetChanged()
                }
                holder.itemView.setOnClickListener {
                    checkBox.isChecked = !checkBox.isChecked
                    item.isSelect = checkBox.isChecked
                    notifyDataSetChanged()
                }
            }

        }
        val linearLayoutManager = LinearLayoutManager(this)
        binding.rvSearchDevice.setLayoutManager(linearLayoutManager)
        binding.rvSearchDevice.setAdapter(mBleDeviceAdapter)


        binding.tvGoBind.onClicked {
            if (mBleDeviceAdapter != null && mBleDeviceAdapter!!.data != null) {
                var selectBleList = ArrayList<BleSLDevice>()
                for (item in mBleDeviceAdapter!!.data) {
                    if (item.isSelect) {
                        selectBleList.add(item)
                    }
                }
                if (selectBleList.size > 0) {
                    if (NetworkUtils.getWifiEnabled()) {
                        startActivity(Intent(this@HomeActivity, WiFiActivity::class.java))
                        EventBus.getDefault().postSticky(EventBusEntity("BLE", selectBleList))
                    } else {
                        ToastUtils.showShort("请打开Wi-Fi")
                    }
                } else {
                    ToastUtils.showShort("请选择要配网的设备")
                }
            }
        }
        binding.tvBleScan.onClicked {
            requestLocationPermission()
        }

        binding.tvGoToCamera.onClicked {
            var deviceId = ""
            if (mBleDeviceAdapter != null && mBleDeviceAdapter!!.data.isNotEmpty()) {
                var selectBleList = ArrayList<BleSLDevice>()
                for (item in mBleDeviceAdapter!!.data) {
                    if (item.isSelect) {
                        selectBleList.add(item)
                    }
                }
                if (selectBleList.size > 0) {
                    if (NetworkUtils.getWifiEnabled()) {
                        if (selectBleList.size > 1) {
                            ToastUtils.showShort("只能选择一台设备进行调试")
                        } else {
                            LogUtil.e("AP扫描开始")
//                            apSearch.start()
                            localConnect(selectBleList[0], "AICAM_" + selectBleList[0].tangeUUID)
                        }
                    } else {
                        ToastUtils.showShort("请打开Wi-Fi")
                    }
                } else {
                    ToastUtils.showShort("请选择要调试的设备")
                }
            }
        }
        apSearch = DeviceBindingSearchAccessPoint(this) {
            TGLog.i(LanApScanActivity.TAG, "[onSearched] $it")
            if (it.success) {
                apSearchList.clear()
                apSearchList.addAll(it.data!!)
                LogUtil.e("扫描到的AP设备：" + GsonUtils.toJson(apSearchList))
            } else {
                Toast.makeText(this@HomeActivity, "扫描失败: ${it.message}", Toast.LENGTH_LONG)
                    .show()
            }
        }
    }

    private fun localConnect(bleSlDevice: BleSLDevice, apName: String) {
        //2.连接设备热点
        var apConnection = DeviceBindingConnectionByAccessPoint(this@HomeActivity, apName)
        apConnection.connect("") {
            loading?.dismiss()
            if (it.success) {
                Toast.makeText(this@HomeActivity, "连接成功，2s后跳转实时播放...", Toast.LENGTH_LONG)
                    .show()
                mainHandler().postDelayed({
                    // 从设备的AP名称中，解析出设备ID
                    // 注意：此处只是示例，要根据自己产品的实际情况调整

                    val deviceId = apName.replace("AICAM_", "")
                    DeviceLiveActivity.launchLanMode(this@HomeActivity, deviceId)
                    finish()
                }, 2000L)
            } else {
                Toast.makeText(
                    this@HomeActivity,
                    "连接失败 ${it.code}, ${it.message}",
                    Toast.LENGTH_LONG
                ).show()
            }
        }
//        DeviceLiveActivity.launchLanMode(
//            this@HomeActivity,
//            bleSlDevice.tangeUUID
//        )

//        val deviceFacade= DeviceFacade(bleSlDevice.tangeUUID)
//        deviceFacade.observeConnectStatus(object :Consumer<ConnectStatus>{
//            override fun accept(status: ConnectStatus) {
//                LogUtil.e("本地连接:"+GsonUtils.toJson(status))
//            }
//        })
//
//        deviceFacade?.let {
//
//            it.preConnect = 1
//            if (it.connected()) {
//                LogUtil.e("本地连接：已经连接过了")
//            } else {
//                it.connect()
//                LogUtil.e("本地连接：开始尝试连接")
//            }
//        }
    }


    inner class BluetoothMonitorReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (action != null) {
                when (action) {
                    BluetoothAdapter.ACTION_STATE_CHANGED -> {
                        val blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)
                        when (blueState) {
                            BluetoothAdapter.STATE_TURNING_ON -> {}
                            BluetoothAdapter.STATE_ON -> {
                                startScan()
                            }

                            BluetoothAdapter.STATE_TURNING_OFF -> {}
                            BluetoothAdapter.STATE_OFF -> {}
                        }
                    }

                    BluetoothDevice.ACTION_ACL_CONNECTED -> {}
                    BluetoothDevice.ACTION_ACL_DISCONNECTED -> {}
                }
            }
        }
    }


    private fun requestLocationPermission() {
        val permissions = mutableListOf<String>()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 12+ 需要申请新权限
            permissions.add(Manifest.permission.ACCESS_FINE_LOCATION)
            permissions.add(Manifest.permission.BLUETOOTH_SCAN)
            permissions.add(Manifest.permission.BLUETOOTH_CONNECT)
        } else {
            // 旧版本需要位置权限
            permissions.add(Manifest.permission.ACCESS_FINE_LOCATION)
        }

        PermissionX.init(this)
            .permissions(permissions)
            .onExplainRequestReason { scope, deniedList ->
                scope.showRequestReasonDialog(
                    deniedList,
                    "需要蓝牙权限以扫描和连接设备",
                    "确定",
                    "取消"
                )
            }
            .request { allGranted, grantedList, deniedList ->
                if (allGranted) {
                    // 所有权限已授予，打开蓝牙
                    val isOpenBle = BleUtil.isBleEnable(this)
                    if (!isOpenBle) {
                        ToastUtils.showShort("蓝牙没打开，请先打开蓝牙")
                        BleUtil.enableBluetooth(this, 1)
                        return@request
                    }
                    //扫描
                    startScan()
                } else {
                    var normalMsgDialog =
                        NormalMsgVPopup(baseContext)
                    normalMsgDialog.showPopupWindow()
                    normalMsgDialog.tvTitle.text = "温馨提示"
                    normalMsgDialog.tvContent.text =
                        "部分权限被拒绝，需要手动打开"
                    normalMsgDialog.tvCancel.visibility = View.VISIBLE
                    normalMsgDialog.tvCancel.text = "取消"
                    normalMsgDialog.tvSure.text = "确定"
                    normalMsgDialog.tvSure.onClicked {
                        normalMsgDialog.dismiss()
                        try {
                            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                            intent.setData(Uri.parse("package:$packageName"))
                            startActivity(intent)
                        } catch (e: java.lang.Exception) {
                            // 处理异常，例如在非Activity的Context中使用
                        }
                    }
                }
            }

    }

    private fun startScan() {
        LogUtil.e("开启扫描")
        binding.tvBleScan.visibility = View.GONE
        binding.tvSearchDevicesStr.text = "搜搜中"
        handler.removeCallbacks(runnable)
        handler.post(runnable)
        BleScan.getInstance().init(this)
        BleScan.getInstance().setVcooBleScanListener(vcooBleScanListenner)
        BleScan.getInstance().startScanBleOnce(20)
    }

    private val vcooBleScanListenner: BleScan.VcooBleScanListenner =
        object : BleScan.VcooBleScanListenner {
            override fun onScanStarted(success: Boolean) {
                binding.llNoDevices.visibility = View.VISIBLE
                binding.llHaveDevice.visibility = View.GONE
                if (success) {
                    LogUtil.e("启动蓝牙扫描成功.....")
                } else {
                    LogUtil.e("启动蓝牙扫描失败！！")
                }
            }

            override fun onScanning(bleDevice: BleDevice?) {
                if (!ActivityUtils.isActivityAlive(this@HomeActivity)) {
                    return
                }
                mBleDeviceAdapter!!.setNewInstance(BleScan.getInstance().bleDeviceList)
                mBleDeviceAdapter!!.notifyDataSetChanged()

                if (BleScan.getInstance().bleDeviceList.size > 0) {
                    binding.llNoDevices.visibility = View.GONE
                    binding.llHaveDevice.visibility = View.VISIBLE
                }
            }

            override fun onScanFinished(scanResultList: List<BleDevice?>?) {
                LogUtil.e("ble搜索结束")
                if (BleScan.getInstance().bleDeviceList.size > 0) {
                    binding.llNoDevices.visibility = View.GONE
                    binding.llHaveDevice.visibility = View.VISIBLE
                } else {
                    binding.llNoDevices.visibility = View.VISIBLE
                    binding.llHaveDevice.visibility = View.GONE
                }
                handler.removeCallbacks(runnable)
                binding.tvSearchDevicesStr.text = "搜索结束"
                binding.tvSearchDevices.text = ""
                binding.tvBleScan.visibility = View.VISIBLE

            }
        }


    private fun gotoManualSearch() {
//        binding.llConnectWifiAuto.gone()
//        binding.tvManualSearch.text = "自动发现"
//        binding.llConnectWifiManual.visible()

        var normalMsgDialog =
            NormalMsgVPopup(baseContext)
        normalMsgDialog.showPopupWindow()
        normalMsgDialog.tvTitle.text = "温馨提示"
        normalMsgDialog.tvContent.text =
            "长按设备reset键5秒，看到设备灯光闪缩后松开手，点击扫一扫扫描设备上的二维码"
        normalMsgDialog.tvCancel.visibility = View.VISIBLE
        normalMsgDialog.tvCancel.text = "取消"
        normalMsgDialog.tvSure.text = "扫一扫"
        normalMsgDialog.tvSure.onClicked {
            normalMsgDialog.dismiss()

            val permissions = mutableListOf<String>()
            permissions.add(Manifest.permission.CAMERA)


            PermissionX.init(this)
                .permissions(permissions)
                .onExplainRequestReason { scope, deniedList ->
                    scope.showRequestReasonDialog(
                        deniedList,
                        "需要相机权限以扫描和连接设备",
                        "确定",
                        "取消"
                        // "取消"
                    )
                }
                .request { allGranted, grantedList, deniedList ->
                    if (allGranted) {
                        // 所有权限已授予
                        startActivityForResult(
                            Intent(this, BindingQrcodeScanActivity::class.java),
                            REQ_CODE
                        )
                    } else {
                        var normalMsgDialog =
                            NormalMsgVPopup(baseContext)
                        normalMsgDialog.showPopupWindow()
                        normalMsgDialog.tvTitle.text = "温馨提示"
                        normalMsgDialog.tvContent.text =
                            "相机权限被拒绝，需要手动打开"
                        normalMsgDialog.tvCancel.visibility = View.VISIBLE
                        normalMsgDialog.tvCancel.text = "取消"
                        normalMsgDialog.tvSure.text = "确定"
                        normalMsgDialog.tvSure.onClicked {
                            normalMsgDialog.dismiss()
                            try {
                                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                                intent.setData(Uri.parse("package:$packageName"))
                                startActivity(intent)
                            } catch (e: java.lang.Exception) {

                            }
                        }
                    }
                }

        }
    }

    val REQ_CODE = 8

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == REQ_CODE && RESULT_OK == resultCode) {
            val id = data?.getStringExtra("device_id") ?: ""
            ToastUtils.showLong("device_id：" + id)
        }
    }

    private fun showCacheDialog() {
        var normalMsgDialog =
            NormalMsgHPopup(baseContext)
        normalMsgDialog.showPopupWindow()
        normalMsgDialog.tvTitle.text = "温馨提示"
        normalMsgDialog.tvContent.text = "确认清除缓存吗"
        normalMsgDialog.tvLeft.visibility = View.VISIBLE
        normalMsgDialog.tvLeft.text = "取消"
        normalMsgDialog.tvRight.text = "清除"
        normalMsgDialog.tvRight.onClicked {
            SysUtils.clearAllCache(baseContext)
            ToastUtils.showLong("清除成功")
            try {
                binding.tvCacheSize.text = SysUtils.getTotalCacheSize(baseContext)
            } catch (e: java.lang.Exception) {
                binding.tvCacheSize.text = ""
                e.printStackTrace()
            }
            normalMsgDialog.dismiss()
        }
    }


    private fun onSearch() {
        BasicDialogInput(this).apply {
            setEditHint(if (TextUtils.isEmpty(searchKeyword)) "输入设备名称关键字" else "当前筛选的是\"${searchKeyword}\"")
            setPositiveText("搜索设备")
            setNegativeText("清空搜索")
            setPositiveOnClicked {
                searchKeyword = it
                refreshWholeDeviceList()
            }
            setNegativeOnClicked {
                searchKeyword = ""
                refreshWholeDeviceList()
            }
            show()
        }
    }

    private fun onAddDevice(it: View) {
        val menu = PopupMenu(it.context, it)
        menu.inflate(R.menu.menu_add_device)
        menu.setOnMenuItemClickListener {
            if (it.itemId == R.id.from_device_binding) {
                binding()
                true
            } else if (it.itemId == R.id.from_share_code) {
                recognizeShareCode()
                true
            }
            false
        }
        menu.gravity = Gravity.END
        menu.show()
    }

    private fun pushServiceBinding() {
        val customAppId = SP.getString(this, Constants.KEY_CUSTOM_APP_ID, "")
        if (!TextUtils.isEmpty(customAppId)) {
            TGLog.i(TAG, "[pushServiceBinding] no need to binding.")
            return
        }

        TGLog.i(TAG, "[pushServiceBinding] bind for appid = ${BuildConfig.TG_APP_ID}")

        val deviceIdByAli = PushServiceFactory.getCloudPushService().deviceId
        if (!TextUtils.isEmpty(deviceIdByAli)) {
            MessagePush.requireBinding(deviceIdByAli, MessagePush.PushChannel.ALI) {
                TGLog.i(TAG, "[pushServiceBinding] $it")
                if (!it.success) {
                    binding.root.postDelayed(
                        { Tips.show("注意：阿里云推送ID提交失败：${it.code} ${it.message}") },
                        1000
                    )
                } else {
                    createNotificationChannel()
                    requireEnableNotifications()
                }
            }
        } else {
            if (pushBindingCanRetry) {  // 最后一次机会：5 秒后再试一次拿推送ID
                TGLog.i(TAG, "[pushServiceBinding] deviceId empty , retry later.")
                pushBindingCanRetry = false
                binding.root.postDelayed({ pushServiceBinding() }, 5000)
            } else {
                TGLog.i(TAG, "[pushServiceBinding] deviceId empty !")
            }
        }
    }

    /**
     * 注意：必须注册消息通道，否则通知栏是无法显示消息的
     * 你可参考阿里云官方文档：https://help.aliyun.com/document_detail/67398.html?spm=a2c4g.434660.0.i0
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val mNotificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            val channelId = "1"
            val name: CharSequence = "设备消息推送通道"
            val description = "设备消息推送通道"
            val importance = NotificationManager.IMPORTANCE_HIGH
            val mChannel = NotificationChannel(channelId, name, importance)
            mChannel.description = description
            mChannel.enableLights(true)
            mChannel.lightColor = Color.RED
            mChannel.enableVibration(true)
            mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
            mNotificationManager.createNotificationChannel(mChannel)
        }
    }

    private fun requireEnableNotifications() {
        binding.root.postDelayed({
            val areNotificationsEnabled =
                NotificationManagerCompat.from(this).areNotificationsEnabled()
            if (!areNotificationsEnabled) {
                BasicDialogRequest(this@HomeActivity).apply {
                    setMessage("启用消息通知，以接收设备事件？")
                    setNegativeText("不用了")
                    setNegativeOnClicked {
                        dismiss()
                    }
                    setPositiveText("好，这就去")
                    setPositiveOnClicked {
                        val intent = Intent().apply {
                            action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
                            putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
                        }
                        startActivity(intent)
                    }
                }.show()
            }
        }, 2000)
    }

    override fun onDestroy() {
        super.onDestroy()
        destroyPreConnect()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(ringReceiver);
    }

    private fun recognizeShareCode() {

        val shareCode = ClipboardUtils.paste(this)
        if (TextUtils.isEmpty(shareCode) || !shareCode.startsWith("SC://")) {
            Tips.show("剪贴板无分享码！")
            return
        }

        DeviceSharing.queryCode(shareCode) {
            if (it.success) {

                it.data?.let {

                    val owner =
                        if (!TextUtils.isEmpty(it.ownerNickName)) it.ownerNickName else "${it.ownerUserId}"
                    val deviceName =
                        if ((it.deviceName?.size ?: 0) > 0) it.deviceName?.get(0) else "未知设备"

                    BasicDialogRequest(this@HomeActivity).apply {
                        setMessage("来自${owner}的\"${deviceName}\"，是否接受？")
                        setPositiveText("收下")
                        setNegativeText("不要了")
                        setPositiveOnClicked {
                            DeviceSharing.acceptCode(shareCode) {
                                if (it.success) {
                                    Tips.show("接收成功！")
                                    devices.clear()
                                    requireDeviceList()
                                } else {
                                    Tips.show("接收失败 ${it.message}")
                                }
                            }
                        }
                    }.show()

                }

            } else {
                Tips.show("分享码识别失败：${it.code} ${it.message}")
            }
        }
    }

    override fun onPause() {
        super.onPause()
        stopRing()
    }

    private fun stopRing() {
        try {
            if (mediaPlayer?.isPlaying == true) {
                mediaPlayer?.stop()
            }
            mediaPlayer?.release()
            mediaPlayer = null
        } catch (e: Exception) {
        }
    }

    private fun binding() {
        if (bindingPrepareRemind) {
            startActivity(Intent(this@HomeActivity, BindingWaysActivity::class.java))
            refreshLater = true
        } else {
            BasicDialogRequest(this@HomeActivity).apply {
                setMessage("请让设备进入\"配网模式\"后，再点击下一步")
                setPositiveText("下一步")
                setPositiveOnClicked {
                    bindingPrepareRemind = true
                    startActivity(Intent(this@HomeActivity, BindingWaysActivity::class.java))
                    dismiss()
                }
            }.show()
        }
    }

    private fun logout() {
        BasicDialogRequest(this@HomeActivity).apply {
            setMessage("确定要退出${if (debuggingMode) "调试" else "登录"}吗？")
            setPositiveText("是的")
            setPositiveOnClicked {
                dismiss()

                if (debuggingMode) {
                    PreferenceUtil.setStringCommit(
                        this@HomeActivity,
                        DebuggingQrcodeScanActivity.PRE_DEBUGGING_CODE,
                        ""
                    )
                    PreferenceUtil.setStringCommit(
                        this@HomeActivity,
                        TokenQrcodeScanActivity.KEY_PRE_ACCESS_TOKEN,
                        ""
                    )
                    Authentication.clear()
                    Tips.show("本地存储的调试信息已清理")
                    finish()
                } else {
                    BuiltinAccount.login().logout {
                        if (!it.success) Tips.show("注销失败：${it.code}, ${it.message}")
                        else Tips.show("用户令牌已成功在线注销")
                        PreferenceUtil.setStringCommit(
                            this@HomeActivity,
                            InternalAccountLoginActivity.PRE_AREA_CODE,
                            ""
                        )
                        PreferenceUtil.setStringCommit(
                            this@HomeActivity,
                            InternalAccountLoginActivity.PRE_USER_NAME,
                            ""
                        )
                        PreferenceUtil.setStringCommit(
                            this@HomeActivity,
                            InternalAccountLoginActivity.PRE_USER_PWD,
                            ""
                        )
                        PreferenceUtil.setStringCommit(
                            this@HomeActivity,
                            InternalAccountLoginActivity.PRE_TOKEN,
                            ""
                        )
                        Authentication.clear()
                        finish()
                    }
                }
            }
            setNegativeText("算了")
            setNegativeOnClicked {
                dismiss()
            }
        }.show()
    }

    override fun onResume() {
        super.onResume()
//        if (refreshLater) {
//            refreshWholeDeviceList()
//        }
//        refreshLater = false
        refreshWholeDeviceList()

        requestLocationPermission()

        if (binding.llConnectWifiLayout.isVisible()) {
            BleScan.getInstance().restartScan()
//            startScan()
        }
    }

    private fun requireDeviceList() {
        binding.emptyView.gone()

        DeviceInfoQuery.requireBasic(devices.size, PAGE_LIMIT, searchKeyword) {
            if (it.success) {
                getDevices()
                ui {
                    val count = it.data?.total ?: 0
                    if (count > 0 && devices.size == 0) {
                        Tips.show("共${count}台设备")
                    }
                }
                if ((it.data?.list?.size ?: 0) > 0) {
                    it.data?.list?.forEach { devices.add(Device(deviceInfoBasic = it)) }
                    it.data?.list?.let { requireDeviceBatteryStatus(it) }
                } else {
                    if (devices.size == 0) {
                        binding.emptyView.visible()
                        binding.apList.gone()
                        binding.swipeRefresh.isRefreshing = false
                        loading?.dismiss()
                    } else {
                        Tips.show("没有更多数据了")
                        binding.swipeRefresh.isRefreshing = false
                        loading?.dismiss()
                    }
                }
            } else {
                loading?.dismiss()
                binding.swipeRefresh.isRefreshing = false
                Tips.show("请求出错 ${it.code}, ${it.message}")
                if (devices.size == 0) {
                    binding.emptyView.visible()
                    binding.apList.gone()
                }
            }
        }
    }

    private fun requireDeviceBatteryStatus(deviceList: List<DeviceInfoBasic>) {
        val list = ArrayList<String>().apply {
            deviceList.forEach { it.deviceId?.let { add(it) } }
        }

        DeviceInfoQuery.requireBattery(list) {
            if (it.success) {
                if ((it.data?.size ?: 0) > 0) {

                    devices.forEach { device ->
                        val key = device.deviceInfoBasic?.deviceId ?: ""
                        if (it.data?.containsKey(key) == true) {
                            device.deviceBattery = it.data?.get(key)
                        }
                    }

                    requireDeviceOnlineStatus(deviceList)
                }


            } else {
                loading?.dismiss()
                binding.swipeRefresh.isRefreshing = false
                Tips.show("请求出错 ${it.code}, ${it.message}")
                loading?.dismiss()
                binding.emptyView.visible()
                binding.apList.gone()
            }
        }
    }

    private fun requireDeviceOnlineStatus(deviceList: List<DeviceInfoBasic>) {
        val list = ArrayList<String>().apply {
            deviceList.forEach { it.deviceId?.let { add(it) } }
        }

        DeviceInfoQuery.requireOnlineStatus(list) {
            if (it.success) {
                if ((it.data?.size ?: 0) > 0) {

                    devices.forEach { device ->
                        val key = device.deviceInfoBasic?.deviceId ?: ""
                        if (it.data?.containsKey(key) == true) {
                            device.deviceOnlineStatus = it.data?.get(key)
                        }
                    }
                    requireDeviceThumbnail(deviceList)
                }


            } else {
                loading?.dismiss()
                binding.swipeRefresh.isRefreshing = false
                Tips.show("请求出错 ${it.code}, ${it.message}")
                loading?.dismiss()
                binding.emptyView.visible()
                binding.apList.gone()
            }
        }
    }

    private fun requireDeviceThumbnail(deviceList: List<DeviceInfoBasic>) {
        val list = ArrayList<String>().apply {
            deviceList.forEach { it.deviceId?.let { add(it) } }
        }

        DeviceInfoQuery.requireThumbnail(list) {
            loading?.dismiss()
            binding.swipeRefresh.isRefreshing = false

            if (it.success) {
                if ((it.data?.size ?: 0) > 0) {

                    devices.forEach { device ->
                        val key = device.deviceInfoBasic?.deviceId ?: ""
                        if (it.data?.containsKey(key) == true) {
                            device.deviceThumbnail = it.data?.get(key)
                        }
                    }

                    TGLog.i(TAG, "[requireDeviceThumbnail] devices = $devices")

                    // 拉取设备列表之后，按策略启用设备预连
                    createPreConnect()

                    listAdapter.refresh(devices)
                    loading?.dismiss()
                    binding.emptyView.gone()
                    binding.apList.visible()
                }
            } else {
                Tips.show("请求出错 ${it.code}, ${it.message}")
                loading?.dismiss()
                binding.emptyView.visible()
                binding.apList.gone()
            }
        }
    }

    /**
     * 建立设备连接
     *
     * 用于演示设备提前连接这一场景（目的是提升后续查看实时时的出图速度）
     * 此处设计的预连策略为：拉下来的前1台设备，如果在线，那么建立连接。
     * 务必注意： 这里只是给出一个示例，建议您结合自身业务场景，设计最适合的预连策略
     */
    private fun createPreConnect() {
        if (!preConnectToDevice) return
        if (devices.size < 1) return

        var index = 0
        devices.forEach { device ->

            val deviceId = device.deviceInfoBasic?.deviceId ?: ""
            val deviceName = device.deviceInfoBasic?.deviceName ?: ""


            if (index < PRE_CONNECT_DEVICE_COUNT) {

                if (device.deviceOnlineStatus?.isOnline == true) {

                    val deviceFacade = if (deviceFacadeMapping.contains(deviceId)) {
                        deviceFacadeMapping[deviceId]
                    } else {
                        DeviceFacade(deviceId).apply {
                            observeConnectStatus(deviceConnectStatusObserver)
                        }
                    }

                    deviceFacade?.let {

                        it.preConnect = 1

                        deviceFacadeMapping[deviceId] = it

                        if (it.connected()) {
                            Log.i(
                                TAG,
                                "[preConnect][create] connected   --- $deviceId, $deviceName"
                            )
                        } else {
                            Log.i(
                                TAG,
                                "[preConnect][create] connecting  --- $deviceId, $deviceName"
                            )
                            it.connect()
                        }
                    }
                } else {
                    Log.i(TAG, "[preConnect][create] offline     --- $deviceId, $deviceName")
                }

            } else {
                Log.i(TAG, "[preConnect][create] ignore      --- $deviceId, $deviceName")
            }
            index++
        }
    }

    /**
     * 销毁设备连接
     */
    private fun destroyPreConnect() {
        if (!preConnectToDevice) return
        if (devices.size < 1) return

        deviceFacadeMapping.keys.forEach {

            val deviceFacade = deviceFacadeMapping[it]
            deviceFacade?.let {
                it.unObserveConnectStatus(deviceConnectStatusObserver)
                it.disconnect()
                Log.i(TAG, "[preConnect][destroy] disconnect --- ${it.deviceId} ")
            }
        }
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean =
        if (KeyEvent.KEYCODE_BACK == keyCode) {
//            logout()
            var normalMsgDialog =
                NormalMsgVPopup(baseContext)
            normalMsgDialog.showPopupWindow()
            normalMsgDialog.tvTitle.text = "温馨提示"
            normalMsgDialog.tvContent.text =
                "您确定要退出APP吗"
            normalMsgDialog.tvCancel.visibility = View.VISIBLE
            normalMsgDialog.tvCancel.text = "取消"
            normalMsgDialog.tvSure.text = "确定"
            normalMsgDialog.tvSure.onClicked {
                normalMsgDialog.dismiss()
                try {
                    AppUtils.exitApp()
                } catch (e: java.lang.Exception) {
                    // 处理异常，例如在非Activity的Context中使用
                }
            }

            true
        } else super.onKeyDown(keyCode, event)


    private inner class LocalBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == INTENT_ACTION_RING) {
                val deviceId = intent.getStringExtra(PARAM_DEVICE_ID) ?: return
                BasicDialogRequest(this@HomeActivity).apply {
                    setMessage("设备 $deviceId 请求通话")
                    setPositiveText("接听")
                    setPositiveOnClicked {
                        stopRing()
                        dismiss()
                        DeviceLiveActivity.launch(this@HomeActivity, deviceId)
                    }
                    setNegativeText("忽略")
                    setNegativeOnClicked {
                        stopRing()
                        dismiss()
                    }
                }.show()

                stopRing()
                mediaPlayer = MediaPlayer.create(context, R.raw.doorbell_5)
                mediaPlayer?.isLooping = true
                mediaPlayer?.start()
            }
        }
    }


    inner class ListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        private val deviceList: MutableList<Device> = ArrayList()
        fun refresh(list: List<Device>) {
            deviceList.clear()
            deviceList.addAll(list)
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(
            viewGroup: ViewGroup,
            viewType: Int
        ): RecyclerView.ViewHolder {
            return if (viewType == VIEW_TYPE_DEVICE) {
                val view: View = LayoutInflater.from(viewGroup.context)
                    .inflate(R.layout.item_device_list_v2, viewGroup, false)
                ViewHolderDevice(view)
            } else {
                val view: View = LayoutInflater.from(viewGroup.context)
                    .inflate(R.layout.item_message_load_more, viewGroup, false)
                ViewHolderLoadMore(view)
            }
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (holder is ViewHolderDevice) {
                val viewHolderDevice: ViewHolderDevice = holder
                val item = deviceList[position]
                var deviceName = item.deviceInfoBasic?.deviceName ?: ""
                val online = item.deviceOnlineStatus?.isOnline == true
                val deviceId = item.deviceInfoBasic?.deviceId ?: ""
                if (TextUtils.isEmpty(deviceName)) {
                    deviceName = "未命名设备"
                }
                viewHolderDevice.name.text =
                    deviceName + "(UUID:" + item.deviceInfoBasic?.deviceId + ")"

                val isOwner = item.deviceInfoBasic?.isOwner == true


                viewHolderDevice.tvDeviceDelete.setOnClickListener {
                    deleteDevice(isOwner, deviceId,item)
                }

                viewHolderDevice.deviceId.text = "MAC:" + item.deviceInfoBasic?.deviceId
                viewHolderDevice.offline.text = if (online) "在线" else "离线"

                if (online) {
                    viewHolderDevice.offline.setTextColor(
                        ContextCompat.getColor(
                            baseContext,
                            R.color.online_green
                        )
                    )
                    viewHolderDevice.ivDeviceOnlineState.setImageResource(R.drawable.shape_green_0dp)
                } else {
                    viewHolderDevice.offline.setTextColor(
                        ContextCompat.getColor(
                            baseContext,
                            R.color.online_red
                        )
                    )
                    viewHolderDevice.ivDeviceOnlineState.setImageResource(R.drawable.shape_red_0dp)
                }

                viewHolderDevice.itemView.setOnClickListener { view: View? ->
                    if (online) {
                        TGLog.i(
                            TAG,
                            "[onBindViewHolder] deviceInfoBasic = ${item.deviceInfoBasic?.deviceAttributes}"
                        )
                        TGLog.i(
                            TAG,
                            "[onBindViewHolder] deviceInfoBasic = ${item.deviceInfoBasic?.deviceAbilities}"
                        )
                        if (item.deviceInfoBasic?.deviceAbilities?.contains("3-composed") == true) { // 识别是否为三目画中画设备
                            SharedChannelDeviceLiveActivity.launch(this@HomeActivity, deviceId)
                        } else if (item.deviceInfoBasic?.deviceAttributes?.contains("-2ch") == true || item.deviceInfoBasic?.deviceAbilities?.contains(
                                "2-composed"
                            ) == true
                        ) { // 识别是否为双目画中画设备
                            MultiChannelDeviceLiveActivity.launch(this@HomeActivity, deviceId)
                        } else {
                            DeviceLiveActivity.launch(
                                this@HomeActivity,
                                deviceId,
                                item.deviceThumbnail?.url ?: ""
                            )
                        }
                    } else {
                        Tips.show("设备已离线！\n使设备上线后，再刷新列表重试")
                    }
                }

                viewHolderDevice.itemView.setOnLongClickListener(OnLongClickListener {
                    deleteDevice(isOwner, deviceId, item)
                    true
                })

                if (item.rowsBean != null){
                    holder.tvShop.text = "商户:" + item.rowsBean!!.deptName
                    holder.tvShopId.text = "商户ID:" + item.rowsBean!!.deptId
                    holder.tvDeviceCount.text = "设备编号:" + item.rowsBean!!.deviceId
                } else {
                    holder.tvShop.text = "商户:"
                    holder.tvShopId.text = "商户ID:"
                    holder.tvDeviceCount.text = "设备编号:"
                }

            } else if (holder is ViewHolderLoadMore) {
                holder.itemView.setOnClickListener {
                    loading?.dismiss()
                    loading?.show()
                    requireDeviceList()
                }
            }
        }

        fun unbindDevice(isOwner: Boolean, deviceId: String, item: Device) {
            if (isOwner) {
                BasicDialogRequest(this@HomeActivity).apply {
                    setMessage("确定要解绑此设备吗？")
                    setPositiveText("是的")
                    setPositiveOnClicked {
                        dismiss()
                        DeviceUnbind.require(deviceId) {
                            if (!it.success) {
                                Tips.show("解绑失败：${it.code}, ${it.message}")
                            } else {
                                Tips.show("设备已成功解绑")
                                unBindMyCloud(item)
                            }
                            refreshWholeDeviceList()
                        }
                    }
                    setNegativeText("算了")
                    setNegativeOnClicked {
                        dismiss()
                    }
                }.show()
            } else {
                BasicDialogRequest(this@HomeActivity).apply {
                    setMessage("确定要退出分享吗？")
                    setPositiveText("是的")
                    setPositiveOnClicked {
                        dismiss()
                        DeviceSharing.quit(deviceId) {
                            if (!it.success) Tips.show("请求失败：${it.code}, ${it.message}")
                            else Tips.show("已退出分享")

                            refreshWholeDeviceList()
                        }
                    }
                    setNegativeText("算了")
                    setNegativeOnClicked {
                        dismiss()
                    }
                }.show()
            }

        }

        override fun getItemCount(): Int {
//            return if (deviceList.size == 0) 0
//            else deviceList.size + 1
            return deviceList.size
        }

//        override fun getItemViewType(position: Int): Int =
//            if (position == (itemCount - 1)) VIEW_TYPE_MORE else VIEW_TYPE_DEVICE

        override fun getItemViewType(position: Int): Int {
            return VIEW_TYPE_DEVICE
        }
    }

    private fun unBindMyCloud(item: Device) {
        val params = java.util.HashMap<String, Any>()
        params["deviceId"] = item.rowsBean!!.deviceId

        deviceService.postUnBindDevice(params)
            .subscribeOn(AndroidSchedulers.mainThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : CustomDisposableForJava<RespMsg<Any>>() {
                override fun onNext(bean: RespMsg<Any>) {
                    try {
                        super.onNext(bean)
                        LogUtil.e("http:" + GsonUtils.toJson(bean))
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
                }

                override fun onError(e: Throwable) {
                    super.onError(e)
                    LogUtil.e(e.toString() + "")
                }
            })

    }

    private fun getDevices() {
        return
        val params = java.util.HashMap<String, Any>()
        params["pageNum"] = 1
        params["pageSize"] = 100

        deviceService.getDeviceList(params)
            .subscribeOn(AndroidSchedulers.mainThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : CustomDisposableForJava<RespMsg<DevicesListBean>>() {
                override fun onNext(bean: RespMsg<DevicesListBean>) {
                    try {
                        super.onNext(bean)
                        LogUtil.e("http:" + GsonUtils.toJson(bean))
                        if (bean.code == "200" && bean.data != null && bean.data.code == "200" && bean.data.rows != null) {
                            for (beanDevices in devices) {
                                for (rowBean in bean.data.rows) {
                                    if (beanDevices.deviceInfoBasic!!.deviceId == rowBean.deviceName){
                                        beanDevices.rowsBean = rowBean
                                    }
                                }
                            }
                            listAdapter.refresh(devices)
                        }


                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
                }

                override fun onError(e: Throwable) {
                    super.onError(e)
                    LogUtil.e(e.toString() + "")
                }
            })

    }

    private fun ListAdapter.deleteDevice(
        isOwner: Boolean,
        deviceId: String,
        item: Device
    ) {
        var normalMsgDialog =
            NormalMsgVPopup(baseContext)
        normalMsgDialog.showPopupWindow()
        normalMsgDialog.tvTitle.text = "温馨提示"
        normalMsgDialog.tvContent.text =
            "是否删除设备，删除设备后需要重新配网"
        normalMsgDialog.tvCancel.visibility = View.VISIBLE
        normalMsgDialog.tvCancel.text = "取消"
        normalMsgDialog.tvSure.text = "确定"
        normalMsgDialog.tvSure.onClicked {
            normalMsgDialog.dismiss()
            unbindDevice(isOwner, deviceId,item)
        }
    }

    private fun refreshWholeDeviceList() {
        binding.swipeRefresh.isRefreshing = true
        devices.clear()
        getDevices()
        requireDeviceList()
    }

    class ViewHolderDevice(view: View) : RecyclerView.ViewHolder(view) {
        val ivDeviceOnlineState: ImageView
        val name: TextView
        val offline: TextView
        val deviceId: TextView
        val tvDeviceDelete: TextView
        val tvDeviceDetail: TextView
        val tvShop: TextView
        val tvShopId: TextView
        val tvDeviceCount: TextView
        val tvTf: TextView


        init {
            deviceId = view.findViewById(R.id.device_id_shown)
            name = view.findViewById(R.id.name)
            offline = view.findViewById(R.id.offline_tips)
            tvDeviceDelete = view.findViewById(R.id.tv_device_delete)
            ivDeviceOnlineState = view.findViewById(R.id.iv_device_online_state)
            tvDeviceDetail = view.findViewById(R.id.tv_device_detail)
            tvShop = view.findViewById(R.id.tv_shop)
            tvShopId = view.findViewById(R.id.tv_shop_id)
            tvDeviceCount = view.findViewById(R.id.tv_device_count)
            tvTf = view.findViewById(R.id.tv_tf)
        }
    }

    class ViewHolderLoadMore(view: View) : RecyclerView.ViewHolder(view)
}